import { useStore } from '@/hooks';
import { Button, Dialog, Form } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid } from '../stores/definitions_group';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';

const FromItem = Form.Item;

const formItemLayout = {
  labelCol: {
    fixedSpan: 10,
  },
  wrapperCol: {
    span: 14,
  },
  style: { marginBottom: 20 },
};

const DataForm = ({ onCancel, modal, onSubmit, ...formProps }) => {
  const { integralStore: store, ruleStore } = useStore();
  const { show, record, toClose } = modal;
  const [group] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(show === 'view');
  useEffect(() => {
    (async () => {
      if (show === 'ruleManage') {
        const res = await store.getGroupId(ruleStore._group_id);
        _.assign(group, res);
      }
    })();
  }, [show]);

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = async (values, item) => {
    const { name, value } = item;
    _.set(group, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: ActivityForm.jsx:213 _ errors:', errors);
      return;
    }
    onSubmit?.(group);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Dialog title={t`积分交易规则管理`} visible={show === 'ruleManage'} onClose={handleCancel} v2>
      <Form
        style={{ marginTop: 20 }}
        {...formProps}
        value={group}
        onChange={handleChange}
        colon={false}
        useLabelForErrorMessage
      >
        <FieldsGrid
          formData={group}
          mode={'add'}
          columns={0}
          colon={false}
          itemLayout={{ ...formItemLayout, labelAlign: 'top' }}
          fields={['tradeMax', 'tradeMin', 'sellableMin', 'purchasableMax'].map((p) => `pointsTradingRule.${p}`)}
        />
        <DrawerFooter>
          <FromItem>
            {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
            <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
          </FromItem>
        </DrawerFooter>
      </Form>
    </Dialog>
  );
};

export default observer(DataForm);
